<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ incomeRanges, counts } = {}) {
      // 为每个柱子设置渐变色
      const colors = [
        ['#FF6B9D', '#FFB3D1'],
        ['#409EFF', '#79BBFF'],
        ['#67C23A', '#95D475'],
        ['#E6A23C', '#F2C674'],
        ['#F56C6C', '#F89898'],
        ['#909399', '#C0C4CC']
      ]

      const seriesData = (counts || []).map((value, index) => ({
        value: value,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [{
              offset: 0, color: colors[index % colors.length][0]
            }, {
              offset: 1, color: colors[index % colors.length][1]
            }]
          }
        }
      }))

      this.chart.setOption({
        title: {
          text: '收入分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
            color: '#666'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const param = params[0]
            const total = counts ? counts.reduce((sum, count) => sum + count, 0) : 0
            const percent = total > 0 ? ((param.value / total) * 100).toFixed(1) : 0
            return `${param.name}<br/>人数: ${param.value}<br/>占比: ${percent}%`
          }
        },
        grid: {
          left: '15%',
          right: '4%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '人数',
          nameTextStyle: {
            color: '#666'
          },
          axisLabel: {
            color: '#999'
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: incomeRanges || [],
          axisLabel: {
            color: '#999'
          },
          axisLine: {
            lineStyle: {
              color: '#e6e6e6'
            }
          }
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            data: seriesData,
            barWidth: '60%',
            label: {
              show: true,
              position: 'right',
              color: '#666',
              fontSize: 12,
              formatter: function(params) {
                const total = counts ? counts.reduce((sum, count) => sum + count, 0) : 0
                const percent = total > 0 ? ((params.value / total) * 100).toFixed(1) : 0
                return `${params.value} (${percent}%)`
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
            },
            animationDelay: function (idx) {
              return idx * 100;
            }
          }
        ],
        animationEasing: 'elasticOut',
        animationDelayUpdate: function (idx) {
          return idx * 5;
        }
      })
    }
  }
}
</script>